#!/usr/bin/perl
#
# Prepare ABNF for wdiff.
# outside of quotes:
#  add space before and after "[][()]"
#   and "<" gets space before, and ">" gets space after
#   and [[(] only get space after if they have [*0-9] before them.
#  strip comments (after ";")
#
# $Fenner$
#
while(<>) {
	chomp;
	@line = split(//);
	$inq = $inp = 0;
	for ($i = 0; $i <= $#line; $i++) {
		if ($line[$i] eq '"') {
			$inq = !$inq;
			next;
		}
		next if ($inq);
		if ($line[$i] eq '<') {
			$inp = 1;
			next;
		}
		if ($inp) {
			if ($line[$i] eq '>') {
				$inp = 0;
			}
			next;
		}
		if ($line[$i] eq ';') {
			splice(@line, $i);
			last;
		}
		if ($line[$i] eq '/') {
			if ($i > 0 && $line[$i-1] ne ' ') {
				splice(@line, $i, 0, " ");
				$i++;
			}
			if ($line[$i+1] ne ' ') {
				splice(@line, $i + 1, 0, " ");
				$i++;
			}
		}
		if ($line[$i] eq '[' || $line[$i] eq '(' || $line[$i] eq '<') {
			if ($i > 0) {
				if ($line[$i-1] =~ /[^*0-9 ]/) {
					splice(@line, $i, 0, " ");
					$i++;
				}
			}
			if ($line[$i] ne '<' && $line[$i+1] ne ' ') {
				splice(@line, $i + 1, 0, " ");
				$i++;
			}
			next;
		}
		if ($line[$i] eq ']' || $line[$i] eq ')' || $line[$i] eq '>') {
			if ($line[$i] ne '>' && (($i > 0) && ($line[$i - 1] ne ' '))) {
				splice(@line, $i, 0, " ");
				$i++;
			}
			if ($line[$i + 1] ne ' ') {
				splice(@line, $i + 1, 0, " ");
				$i++;
			}
			next;
		}
#		if ($quoted[$i] =~ s/;.*//) {
#			splice(@quoted, $i + 1);	# XXX $i or $i + 1?
#			last;
#		}
#		$quoted[$i] =~ s/([^*0-9])([[(])/$1 $2 /g;
#		$quoted[$i] =~ s/([*0-9])([[(])/$1$2 /g;
#		$quoted[$i] =~ s/[])]/ $& /g;
#		$quoted[$i] =~ s/([^*0-9])(<)/$1 $2/g;
#		$quoted[$i] =~ s/>/$& /g;
#		$quoted[$i] =~ s,/, $& ,g;
	}
	print join("", @line), "\n";
}
